package com.yunshipei.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by cike on 15-10-19.
 */
public class CheckSdCard {
    private static CheckSdCard checkSdCard;

    private CheckSdCard() {
    }

    public static CheckSdCard getInstance() {
        if (checkSdCard == null)
            checkSdCard = new CheckSdCard();
        return checkSdCard;
    }

    public boolean checkSD() {
        return Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
    }

    public File Mkdir(String dir) {
        String rootDir;
        if (checkSD())
            rootDir = Environment.getExternalStorageDirectory().toString();
        else
            rootDir = Environment.getDataDirectory().getAbsolutePath();
        rootDir = rootDir + dir;
        File dirFile = new File(rootDir);
        if (!dirFile.exists())
            dirFile.mkdirs();
        return dirFile;
    }

    public Bitmap getBitMapFromLocal(String key) {
        String imagePath = FileUtils.getEnterImgCachePath() + "/" + key + ".jpg";
        File file = new File(imagePath);
        if (file.exists()) {
            Bitmap bm = BitmapFactory.decodeFile(imagePath);
            return bm;
        }
        return null;

    }

    public void addBitmapToLocal(Bitmap bitmap, String key) {
        String imagePath = FileUtils.getEnterImgCachePath() + "/" + key + ".jpg";
        File file = new File(imagePath);
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (bitmap != null) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
        }
        try {
            fOut.flush();
            fOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
